# -*- coding: latin-1 -*-
import time, re
from greader2kindle.feed import FeedCollection, FeedEntry

class DocGenerator:

    def __init__(self, outdir, feedCollections):
        self.outdir = outdir
        self.feedCollections = feedCollections
        self.name = "g2kBlog " + time.strftime("%a, %d %b %Y")
    
    def generate(self):
        self.createAndOpenFile()
        self.generatePreContent()
        self.generateContent()
        self.generatePostContent()
        return self.fname
    
    def createAndOpenFile(self):
        self.fname = self.outdir + "/" + self.name + ".html"
        self.f = open(self.fname, 'w');
    
    def generatePreContent(self):
        self.f.write("<html>\n")
        self.f.write(" <head>\n")
        self.f.write("  <title>" + self.name + "</title>\n")
        self.f.write(" </head>\n\n")
        self.f.write(" <body>\n")
    
    def generateContent(self):
        self.generateTOC()
        self.generateText()
        
    def generateTOC(self):
        self.anchors = 0;
        for feedCollection in self.feedCollections:
            feedCollection.anchor = 'a' + str(self.anchors)
            self.anchors += 1
            self.f.write('<center><h4><a href="#' + feedCollection.anchor + '"> ')
            self.f.write(self.escape(feedCollection.title))
            self.f.write(" </a></h4></center>\n");
            for entry in feedCollection.entries:
                entry.anchor = 'b' + str(self.anchors)
                self.anchors += 1
                self.f.write('<a href="#' + entry.anchor + '"><small> ')
                self.f.write(self.escape(entry.title))
                self.f.write(" </small></a><br/>\n");
            self.f.write("\n")
        self.f.write("\n<mbp:pagebreak/>\n\n")

    def generateText(self):
        for feedCollection in self.feedCollections:
            self.f.write('<a name="' + feedCollection.anchor + '"><h4>')
            self.f.write(self.escape(feedCollection.title))
            self.f.write(" </h4></a>\n")
            for entry in feedCollection.entries:
                self.f.write('<hr /><a name="' + entry.anchor + '"><center><h5>')
                self.f.write(self.escape(entry.title))
                self.f.write(" </h5></center></a>\n")
                self.f.write('<p style="text-indent:0px">\n')
                self.f.write(self.processContent(entry.content))
                self.f.write("\n</p>\n")
    
    def processContent(self, c):
        c = self.escape(c)
        # strip iframes
        c = re.sub(r'</*iframe[^<]*>', r'' , c)
        # strip links
        c = re.sub(r'</*a[^>]*>', r'' , c)
        # strip pseudo images
        c = re.sub(r'<img [^>]* height="1"[^>]*>', r'' , c)
        # strip/share stuff
        c = re.sub(r'<[^>]*facebook[^>]*>', r'' , c)
        c = re.sub(r'<[^>]*twitter[^>]*>', r'' , c)
        c = re.sub(r'<[^>]*feedsportal[^>]*>', r'' , c)
        c = re.sub(r'<[^>]*post\_label\_source[^>]*>', r'' , c)
        c = re.sub(r'<[^>]*doubleclick\.net[^>]*>', r'' , c)
        # strip paragraphs with background color
        c = re.sub(r'<p[^>]+style="[^"]*background[^"]*"[^>]*>.*?</p>', r'', c)
        # blog specific stuff
        c = re.sub(r'<p>Read more of this story at Slashdot.</p>', r'', c)
        c = re.sub(r'<p>Continue reading <em>.*?</p>', r'', c)
        c = re.sub(r'<h6.*?Permalink.*?Email this\|Comments', r'', c)
        
        """
        TODO: implement proper image handling, i.e. fetch them locally and
              include them in the output file
              For now: replace images by their ALTernative text
        """
        c = re.sub(r'<img[^<]*alt="(.*?)"[^<]*>', r'\1', c)
        c = re.sub(r'</*img[^<]*>', r'' , c)
        
        # strip now empty paragraphs
        c = re.sub(r'</*br */* *>[\t\n ]*</p>', r'</p>', c)
        c = re.sub(r'<p>[\t\n ]*</p>', r'' , c)
        # strip line breaks
        c = re.sub(r'(<\/*br *\/*>[\t\n ]*)+', r'</br>' , c)
        # dont indent paragraphs
        c = re.sub(r'<p.*?>', r'<p style="text-indent:0px">', c)
        return c
    
    def escape(self, txt):
        return txt.encode("ascii", "ignore")
    
    def generatePostContent(self):
        self.f.write("\n </body>\n\n")
        self.f.write("</html>")